package com.example.swd1.gudong.main;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.example.swd1.gudong.R;
import com.example.swd1.gudong.Tool.DatabaseHelper;
import com.example.swd1.gudong.base.BaseFragmentActivity;
import com.example.swd1.gudong.constant.Constant;
import com.example.swd1.gudong.main.MainFragmentTabAdapter.OnTabChangedListener;
import com.example.swd1.gudong.main.found.FoundFragment;
import com.example.swd1.gudong.main.message.MessageFragment;
import com.example.swd1.gudong.main.sport.SportFragment;
import com.example.swd1.gudong.main.sportrang.SportRangFragment;
import com.example.swd1.gudong.main.user.UserFragment;
import com.example.swd1.gudong.model.MessageItem;
import com.example.swd1.gudong.view.TabView;

import java.util.ArrayList;
import java.util.List;

//==================================================================================================================
//   Author :  Shile Wu
//   Date  :  16-8-23
//   Role :  MainActivity
//   Reference documents : None
//==================================================================================================================
public class MainActivity extends BaseFragmentActivity implements OnTabChangedListener, View.OnClickListener {

    private TabView tabView;
    private List<Fragment> fragments;
    private int currentFragment = 2;

    private int currentFragmentInSport = Constant.VIEW_PAGE_FLAG_SPORT;
    private int currentFragmentInSportRang = Constant.VIEW_PAGE_FLAG_DYNAMIC;

    private BroadcastReceiver messageReciever;
    private IntentFilter intentFilter;
    private MessageFragment messageFragment;
    private PopupWindow popupWindow;

    private DatabaseHelper helper;
    private SQLiteDatabase db;
    private static boolean firstLoadSportRang = true;
    private static boolean firstLoadMe = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        changeTitleAndMenu(Constant.BTN_FLAG_SPORT);//default page
        initView();
        initData();
    }

    /*
    * no save instance state ,or the fragment page will superpose
    * */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    private void initView() {
        tabView = (TabView) findViewById(R.id.tab_view);
        tabView.initBottomPanel();
        tabView.defaultBtnChecked(Constant.BTN_FLAG_SPORT);

        fragments = new ArrayList<Fragment>();
        messageFragment = new MessageFragment();
        fragments.add(new SportRangFragment());
        fragments.add(new FoundFragment());
        fragments.add(new SportFragment());
        fragments.add(messageFragment);
        fragments.add(new UserFragment());

        //the adapter to load fragments
        MainFragmentTabAdapter tabAdapter = new MainFragmentTabAdapter(this, fragments, R.id.fragment_content, tabView);
        //listen the fragments change
        tabAdapter.setOnTabChangedListener(this);

        for (View view : getToolBarViewList()) {
            view.setOnClickListener(this);
        }
    }

    private void initData() {
        helper = DatabaseHelper.getInstance(this);
        List<MessageItem> messageItemList = readMessageList();
        if (messageItemList != null) {
            messageFragment.setMessageList(messageItemList, this);
        }
        recieveMessage();
    }

    /*
    * recieve message from service which in another app
    * */
    private void recieveMessage() {
        intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.swd1.gudong.MessageBroadCaseReciever");
        messageReciever = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                tabView.setUnReadMessageStatus(true, tabView.getUnReadMessageStatus() + 1);
                String[] value = intent.getStringArrayExtra("messageItem");
                MessageItem item = new MessageItem();
                item.setMessageTitle(value[0]);
                item.setMessageContent(value[1]);
                item.setMessageTime(value[2]);
                item.setUnReadNum(1);
                messageFragment.setMessageList(item, MainActivity.this);
            }
        };
        if (messageFragment != null) {
            registerReceiver(messageReciever, intentFilter);
        }
    }


    @Override
    public void OnTabCheckedChanged(TabView tabView, final int index) {
        /*-begin-20160918-shile.wu-add-for-task2781345-*/
        //to resolve the problems that first load sport rang fragment and me fragment are so late
        //old: currentFragment = index;
        //     changeTitleAndMenu(index);
        if (index == 0) {
            if (firstLoadSportRang) {
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        try {
                            sleep(200);
                            Message message = new Message();
                            message.what = 1;
                            message.arg1 = index;
                            mHandler.sendMessage(message);
                            firstLoadSportRang = false;
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                };
                thread.start();
            } else {
                currentFragment = index;
                changeTitleAndMenu(index);
            }
        } else if (index == 4) {
            if (firstLoadMe) {
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        try {
                            sleep(200);
                            Message message = new Message();
                            message.what = 1;
                            message.arg1 = index;
                            mHandler.sendMessage(message);
                            firstLoadMe = false;
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                };
                thread.start();
            } else {
                currentFragment = index;
                changeTitleAndMenu(index);
            }
        } else {
            currentFragment = index;
            changeTitleAndMenu(index);
        }
    }

    private mHandler mHandler = new mHandler();

    private class mHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                currentFragment = msg.arg1;
                changeTitleAndMenu(msg.arg1);
            }
        }
    }
    /*-end-20160913-shile.wu-add-for-task2781345-*/


    /*
    * according to tab change,show and hide menu and change title
    * */
    public void changeTitleAndMenu(int flag) {
        switch (flag) {
            case Constant.BTN_FLAG_SPORTRANG:
                setTitle("");
                showSportRangMenu();
                showSportRangTitle(currentFragmentInSportRang);
                break;
            case Constant.BTN_FLAG_FOUND:
                setTitle(Constant.FRAGMENT_TITLE_FOUND);
                setTitleSize(20);
                showFoundMenu();
                break;
            case Constant.BTN_FLAG_SPORT:
                setTitle(getSportFragmentTitle(currentFragmentInSport));
                setTitleSize(16);
                showSportMenu(currentFragmentInSport);
                break;
            case Constant.BTN_FLAG_MESSAGE:
                setTitle(Constant.FRAGMENT_TITLE_MESSAGE);
                setTitleSize(20);
                showMessageMenu();
                break;
            case Constant.BTN_FLAG_ME:
                setTitle("");
                showUserMenu();
                break;
            case Constant.VIEW_PAGE_FLAG_SPORT:
                setTitle(Constant.VIEW_PAGE_TITLE_SPORT);
                showSportMenu(Constant.VIEW_PAGE_FLAG_SPORT);
                break;
            case Constant.VIEW_PAGE_FLAG_TRAIN:
                setTitle(Constant.VIEW_PAGE_TITLE_TRAIN);
                showSportMenu(Constant.VIEW_PAGE_FLAG_TRAIN);
                break;
            case Constant.VIEW_PAGE_FLAG_TARGET:
                setTitle(Constant.VIEW_PAGE_TITLE_TARGET);
                showSportMenu(Constant.VIEW_PAGE_FLAG_TARGET);
                break;
            case Constant.VIEW_PAGE_FLAG_DYNAMIC:
                showSportRangTitle(currentFragmentInSportRang);
                break;
            case Constant.VIEW_PAGE_FLAG_SQUARE:
                showSportRangTitle(currentFragmentInSportRang);
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.menu_add_friends_img:
                break;
            case R.id.menu_camera_img:
                break;
            case R.id.menu_search_img:
                break;
            case R.id.menu_scan_img:
                break;
            case R.id.menu_run_img:
                showSportTypePopupWindow();
                break;
            case R.id.menu_setting_img:
                showSettingPopupWindow();
                break;
            case R.id.text_contacts:
                break;
            case R.id.text_setting:
                break;
        }
        Log.d("555log", v.getId() + "");
    }

    /*
    * set the flag which indicate current fragment in sportFragment
    * */
    public void setCurrentFragmentInSport(int index) {
        currentFragmentInSport = index;
    }

    /*
     * set the flag which indicate current fragment in sportRangFragment
     * */
    public void setCurrentFragmentInSportRang(int index) {
        currentFragmentInSportRang = index;
    }

    private String getSportFragmentTitle(int index) {
        switch (index) {
            case Constant.VIEW_PAGE_FLAG_SPORT:
                return Constant.VIEW_PAGE_TITLE_SPORT;
            case Constant.VIEW_PAGE_FLAG_TRAIN:
                return Constant.VIEW_PAGE_TITLE_TRAIN;
            case Constant.VIEW_PAGE_FLAG_TARGET:
                return Constant.VIEW_PAGE_TITLE_TARGET;
        }
        return "";
    }

    public void hideFootAndHead() {
        tabView.setVisibility(View.GONE);
        hideHeadLayout();
    }

    public void showFootAndHead() {
        tabView.setVisibility(View.VISIBLE);
        showHeadLayout();
    }

    /*
    * get the number at message button
    * */
    public void readMessageNum(int num) {
        int lessUnReadNum = tabView.getUnReadMessageStatus() - num;
        if (lessUnReadNum > 0) {
            tabView.setUnReadMessageStatus(true, lessUnReadNum);
        } else if (lessUnReadNum == 0) {
            tabView.setUnReadMessageStatus(false, 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(messageReciever);
        saveMessageList();
        Log.d("555log", "MainActivity:onDestroy");
    }

    public Fragment getCurrentFragment() {
        return fragments.get(currentFragment);
    }

    private void showSettingPopupWindow() {
        backgroundAlpha(0.5f);
        View popupWindow_view = getLayoutInflater().inflate(R.layout.popwindow_setting, null, false);
        popupWindow = new PopupWindow(popupWindow_view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setAnimationStyle(R.style.popWindowAnimation);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.showAtLocation(popupWindow_view, Gravity.BOTTOM, 0, 0);
        popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    backgroundAlpha(1);
                    popupWindow.dismiss();
                    popupWindow = null;
                }
                return false;
            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1);
            }
        });
    }

    private void showSportTypePopupWindow() {
        backgroundAlpha(0.5f);
        View popupWindow_view = getLayoutInflater().inflate(R.layout.popwindow_sport_type, null, false);
        popupWindow = new PopupWindow(popupWindow_view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setAnimationStyle(R.style.popWindowAnimation);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.showAtLocation(popupWindow_view, Gravity.BOTTOM, 0, 0);
        popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    backgroundAlpha(1);
                    popupWindow.dismiss();
                    popupWindow = null;
                }
                return false;
            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

                backgroundAlpha(1);
            }
        });

    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    public void saveMessageList() {
        List<MessageItem> messageItemList = messageFragment.getMessageItemList();
        if (messageItemList != null) {
            db = helper.getWritableDatabase();
            db.delete(Constant.DATABASE_TABLE_NAME_MESSAGE_LIST, null, null);
            for (MessageItem item : messageItemList) {
                ContentValues values = new ContentValues();
                values.put(Constant.DATABASE_TABLE_FIELD_MESSAGE_TITLE, item.getMessageTitle());
                values.put(Constant.DATABASE_TABLE_FIELD_MESSAGE_CONTENT, item.getMessageContent());
                values.put(Constant.DATABASE_TABLE_FIELD_MESSAGE_TIME, item.getMessageTime());
                values.put(Constant.DATABASE_TABLE_FIELD_MESSAGE_UNREADNUM, item.getUnReadNum());
                db.insert(Constant.DATABASE_TABLE_NAME_MESSAGE_LIST, null, values);
            }
        }
    }

    public List<MessageItem> readMessageList() {
        db = helper.getReadableDatabase();
        Cursor cursor = db.query(Constant.DATABASE_TABLE_NAME_MESSAGE_LIST, null, null, null, null, null, Constant.DATABASE_TABLE_FIELD_MESSAGE_TIME);
        List<MessageItem> messageItemList = new ArrayList<>();
        while (cursor.moveToNext()) {
            MessageItem item = new MessageItem();
            item.setMessageTitle(cursor.getString(cursor.getColumnIndex(Constant.DATABASE_TABLE_FIELD_MESSAGE_TITLE)));
            item.setMessageContent(cursor.getString(cursor.getColumnIndex(Constant.DATABASE_TABLE_FIELD_MESSAGE_CONTENT)));
            item.setMessageTime(cursor.getString(cursor.getColumnIndex(Constant.DATABASE_TABLE_FIELD_MESSAGE_TIME)));
            item.setUnReadNum(cursor.getInt(cursor.getColumnIndex(Constant.DATABASE_TABLE_FIELD_MESSAGE_UNREADNUM)));
            messageItemList.add(item);
        }
        cursor.close();
        return messageItemList;
    }

    private static long pressedTime = 0;
    private static long lastPressed = 0;

    @Override
    public void onBackPressed() {
        pressedTime = System.currentTimeMillis();
        if (pressedTime - lastPressed > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
        } else {
            finish();
            System.exit(0);
        }
        lastPressed = pressedTime;
    }
}
